<template>
  <div>
    <h1>统计图表</h1>
    <div ref="chart" id="bie" style="width: 50%; height: 400px; margin-left: auto; margin-right: auto;"></div>
  </div>
</template>


<script lang="ts" setup>
import * as echarts from 'echarts/core';
import { GridComponent } from 'echarts/components';
import { BarChart } from 'echarts/charts';
import { CanvasRenderer } from 'echarts/renderers';
import { PieChart } from 'echarts/charts';
import { onMounted, ref, computed, onUpdated, watch, onUnmounted } from 'vue';
echarts.use([GridComponent, BarChart, CanvasRenderer, PieChart]);

const data1 = ref<string[]>([]);
const data2 = ref<number[]>([]);
const chart = ref<HTMLDivElement | null>(null);
const myChart = ref<echarts.ECharts | null>(null); // 创建一个 ref 来存储 myChart
data1.value = ['蔬菜类', '零食类', '玩具类', '生活类', '其它类']
data2.value = JSON.parse(localStorage.getItem('dataValue') as string)
onMounted(() => {
    myChart.value = echarts.init(chart.value); // 初始化图表
    myChart.value.setOption(option.value); // 设置图表选项
})
watch(data2, (newVal, oldVal) => {
    if (newVal !== oldVal) {
      if(myChart.value){
        myChart.value.setOption(option.value); // 设置图表选项
      }
    }
})
let tim = setInterval(() => {
    data2.value = JSON.parse(localStorage.getItem('dataValue') as string)
}, 900)

onUnmounted(() => {
  clearInterval(tim)
})

const option = computed(() => {
    return {
    xAxis: {
    type: 'category',
    data: data1.value
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: data2.value,
      type: 'bar',
      showBackground: true,
      backgroundStyle: {
        color: 'rgba(180, 180, 180, 0.2)'
      }
    }
  ]
}
})
</script>

<style scoped lang="scss">
</style>
